﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Xrm.Framework.Test.Integration;
using Xrm.Solutions.FrameworkSample.Common.Entities;


namespace Xrm.Solutions.FrameworkSample.XrmIntegrationTests.Plugins
{
    [TestClass]
    public class TestRunIdentityCheck : AsyncPluginIntegrationTest
    {
        #region Instance Variables

        private Contact contact;

        #endregion

        #region Setup

        protected override OrganizationRequest SetupTriggerRequest()
        {
            contact = CreateTestContact();
            
            xdft_identitycheck identityCheck = new xdft_identitycheck();
            identityCheck.xdft_FirstName = contact.FirstName;
            identityCheck.xdft_LastName = contact.LastName;
            identityCheck.xdft_DateOfBirth = contact.BirthDate;
            identityCheck.xdft_Address = contact.Address1_Line1 + " " + contact.Address1_PostalCode;
            identityCheck.xdft_ContactId = contact.ToEntityReference();

            CreateRequest createRequest = new CreateRequest();
            createRequest.Target = identityCheck;

            return createRequest;
        }

        private Contact CreateTestContact()
        {
            Contact contact = new Contact();

            contact.FirstName = DateTime.Now.ToString();
            contact.LastName = "Test";
            contact.BirthDate = DateTime.Now;
            contact.Address1_Line1 = "Soho ";
            contact.Address1_PostalCode = "CW8 0ES";
            contact.Id = this.OrganizationService.Create(contact);

            return contact;
        }

        #endregion

        #region Test

        [TestMethod]
        public void RunTestRunIdentityCheck()
        {
            base.Test();
        }

        #endregion

        #region Verify

        protected override void VerifyStatus()
        {
            Assert.IsNull(Error);

            Assert.AreEqual(Status, AsyncStatus.Pass);

            Contact updatedContact = this.OrganizationService.Retrieve("contact", contact.Id, new ColumnSet(new string[]{ "xdft_identityscore" })).ToEntity<Contact>();

            Assert.IsTrue(updatedContact.xdft_IdentityScore > 0 && updatedContact.xdft_IdentityScore <= 100);
        }

        #endregion


        #region Clean Up

        protected override void CleanUp()
        {
            base.CleanUp();

            Guid identityCheckID = (Guid) this.TriggerResponse.Results["id"];

            this.OrganizationService.Delete("xdft_identitycheck", identityCheckID);

            this.OrganizationService.Delete("contact", contact.Id);
        }

        #endregion
    }
}
